package com.bjpowernode.boss.exceptions;

import com.bjpowernode.boss.enums.RespCode;
import com.bjpowernode.boss.web.model.response.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;

import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;



import java.util.List;

//全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandle {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    @ExceptionHandler( {BossException.class} )
    public CommonResult doBossException(BossException bossException) {
        logger.error("[doBossException]Boss异常:{}",
                bossException.getRespCode(),
                bossException.getRespCode().getMsg());
        return CommonResult.fail(bossException.getRespCode());
    }
    //处理Bean Validation异常
    @ExceptionHandler({BindException.class})
    public CommonResult doBeanValidationException(BindException bind) {
        StringBuilder builder = new StringBuilder("");

        List<FieldError> fieldErrors = bind.getFieldErrors();//获取不满足注解约束的属性
        for (FieldError fe : fieldErrors){
            //错误项loginName或loginPwd
            builder.append("错误项[").append(fe.getField()).append("]")
                    //错误原因即loginQuery中使用的Bean Validation注解的message(NotNull和size)
                    .append("; 原因：[").append(fe.getDefaultMessage()).append("]")
                    //每个错误信息间分割符
                    .append("#");
        }
        CommonResult result = new CommonResult();
        result.setCode(RespCode.REQUEST_PARAM_ERROR.getNumber());
        result.setMsg(builder.toString());
        result.setData("");
        return result;
    }
}
